package system_sms_service

import (
	"gitee.com/Luna-CY/Golang-Project-Template/internal/configuration"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/interface/dao"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/service"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/service/system_sms_service/provider"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/service/system_sms_service/provider/aliyun"
)

func New(smsLog dao.SystemSmsLog) *Sms {
	return &Sms{
		BaseService: service.New(smsLog),
		smsLog:      smsLog,
	}
}

type Sms struct {
	*service.BaseService
	smsLog dao.SystemSmsLog
}

func (cls *Sms) GetProvider(templateCode string) (provider.Provider, errors.Error) {
	// 不要做配置的静态化，配置参数有可能会动态变更
	for _, config := range configuration.Configuration.Sms.Providers {
		var mapping = make(map[string]struct{})
		for _, code := range config.TemplateCodes {
			mapping[code.TemplateCode] = struct{}{}
		}

		if _, ok := mapping[templateCode]; ok && config.Enable {
			switch config.Type {
			case "aliyun":
				p, err := aliyun.New(config)
				if nil != err {
					logger.SugarLogger(logger.WithStack()).Errorf("ISS_MS.S_MS.GP_ER.371215 创建短信提供商失败，模板: %s，错误: %v", templateCode, err)

					continue
				}

				return p, nil
			}
		}
	}

	return nil, errors.ErrorServerInternalError("ISS_MS.S_MS.GP_ER.331404", "未找到有效的短信服务提供商，模板: %s", templateCode)
}
